# -*- coding: utf-8 -*-
"""
模块：DIY电子贺卡制作与分享
"""

import os
from storage_manager import load_templates, load_my_ecards, save_my_ecard, view_my_saved_ecards_interaction
from template_manager import select_template_interaction
from ecard_generator import fill_template_content_interaction, preview_and_generate_ecard_interaction

# 全局变量
selected_template = None
user_filled_values = None

def display_main_menu():
    """显示主菜单"""
    print("\n" + "=" * 30)
    print("DIY电子贺卡制作与分享")
    print("=" * 30)
    print("1. 选择贺卡模板")
    print("2. 填写贺卡内容")
    print("3. 预览并生成贺卡文本")
    print("4. 管理我的贺卡(查看已保存)")
    print("5. 退出程序")
    print("=" * 30)

def main_loop():
    """主循环"""
    global selected_template, user_filled_values
    
    # 初始化数据目录
    if not os.path.exists("data"):
        os.makedirs("data")
    
    # 加载模板
    templates = load_templates()
    my_ecards = load_my_ecards() if os.path.exists("data/my_ecards.json") else []
    
    while True:
        display_main_menu()
        choice = input("请输入您的选择(1-5): ").strip()
        
        if choice == "1":
            selected_template = select_template_interaction(templates)
            user_filled_values = None  # 重置填写的内容
            
        elif choice == "2":
            if not selected_template:
                print("请先选择贺卡模板！")
                continue
            user_filled_values = fill_template_content_interaction(selected_template)
            
        elif choice == "3":
            if not selected_template:
                print("请先选择贺卡模板！")
                continue
            if not user_filled_values:
                print("请先填写贺卡内容！")
                continue
                
            generated_text = preview_and_generate_ecard_interaction(
                selected_template, user_filled_values
            )
            
            # 探索功能：询问是否保存
            save_choice = input("是否将此贺卡保存到'我的贺卡'中？(y/n): ").lower()
            if save_choice == 'y':
                save_my_ecard({
                    'template_used': selected_template['template_id'],
                    'generated_text': generated_text
                })
                
        elif choice == "4":
            view_my_saved_ecards_interaction()
            
        elif choice == "5":
            print("感谢使用DIY电子贺卡制作工具，再见！")
            break
            
        else:
            print("无效的选择，请输入1-5之间的数字！")

if __name__ == "__main__":
    main_loop()
    
def load_templates_internal():
    """硬编码的模板数据"""
    return [
        {
            "template_id": "tpl_birthday_01",
            "name": "简约生日祝福",
            "content": "亲爱的[收件人姓名]，\n\n祝你生日快乐，愿你天天开心，岁岁平安！\n\n来自你真诚的朋友，\n[您的署名]\n\n([附加祝福语])",
            "placeholders": ["收件人姓名", "您的署名", "附加祝福语"]
        },
        {
            "template_id": "tpl_festival_01",
            "name": "通用节日祝福",
            "content": "值此[节日名称]佳节之际，\n[收件人姓名]，祝您和您的家人[节日祝福语]！\n\n[您的署名]\n[日期]",
            "placeholders": ["节日名称", "收件人姓名", "节日祝福语", "您的署名", "日期"]
        },
        {
            "template_id": "tpl_thanks_01",
            "name": "感谢卡",
            "content": "尊敬的[收件人姓名]，\n\n衷心感谢您[感谢原因]。\n您的[具体帮助]让我深受感动。\n\n此致\n敬礼！\n[您的署名]\n[日期]",
            "placeholders": ["收件人姓名", "感谢原因", "具体帮助", "您的署名", "日期"]
        }
    ]

def display_templates(templates):
    """显示所有可用模板"""
    print("\n" + "=" * 30)
    print("可用贺卡模板")
    print("=" * 30)
    for idx, template in enumerate(templates, 1):
        print(f"{idx}. {template['name']}")
        print(f"   模板ID: {template['template_id']}")
        print(f"   占位符: {', '.join(template['placeholders'])}")
    print("=" * 30)

def select_template_interaction(templates):
    """
    模板选择交互
    :param templates: 模板列表
    :return: 选择的模板字典或None
    """
    if not templates:
        print("没有可用模板！")
        return None
        
    display_templates(templates)
    
    while True:
        try:
            choice = input("请输入要选择的模板编号(1-{}): ".format(len(templates))).strip()
            idx = int(choice) - 1
            if 0 <= idx < len(templates):
                return templates[idx]
            print("无效的编号，请重新输入！")
        except ValueError:
            print("请输入有效的数字！")

def get_placeholder_values(template_dict):
    """
    获取用户输入的占位符值
    :param template_dict: 模板字典
    :return: 包含用户输入值的字典
    """
    filled_values = {}
    for placeholder in template_dict['placeholders']:
        value = input(f"请输入 [{placeholder}]: ").strip()
        filled_values[f"[{placeholder}]"] = value
    return filled_values

def fill_template_content_interaction(selected_template):
    """
    填写贺卡内容交互
    :param selected_template: 选中的模板
    :return: 包含用户输入值的字典
    """
    print("\n" + "=" * 30)
    print(f"正在填写 [{selected_template['name']}] 模板")
    print("=" * 30)
    return get_placeholder_values(selected_template)

import json
import os
from datetime import datetime
import time

DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
TEMPLATES_FILE_PATH = os.path.join(DATA_DIR, "templates.json")
MY_ECARDS_FILE_PATH = os.path.join(DATA_DIR, "my_ecards.json")


def load_templates():
    """加载模板数据"""
    if os.path.exists(TEMPLATES_FILE_PATH):
        try:
            with open(TEMPLATES_FILE_PATH, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            print("警告：模板文件读取失败，使用内置模板")
    
    # 如果文件不存在或读取失败，使用硬编码模板
    from template_manager import load_templates_internal
    return load_templates_internal()

def load_my_ecards():
    """加载用户保存的贺卡"""
    if not os.path.exists(MY_ECARDS_FILE_PATH):
        return []
        
    try:
        with open(MY_ECARDS_FILE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        print("警告：我的贺卡文件读取失败，将使用空列表")
        return []

def save_my_ecard(ecard_data_to_save):
    """保存用户贺卡"""
    my_ecards = load_my_ecards()
    
    # 生成ID和时间戳
    ecard_id = f"ecard_{int(time.time())}"
    saved_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 构建完整数据
    ecard_data = {
        "ecard_id": ecard_id,
        "saved_at": saved_at,
        **ecard_data_to_save
    }
    
    my_ecards.append(ecard_data)
    
    try:
        with open(MY_ECARDS_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(my_ecards, f, ensure_ascii=False, indent=2)
        print(f"贺卡已保存，ID: {ecard_id}")
    except IOError:
        print("警告：贺卡保存失败")

def view_my_saved_ecards_interaction():
    """查看已保存贺卡交互"""
    my_ecards = load_my_ecards()
    
    if not my_ecards:
        print("\n您还没有保存任何贺卡！")
        return
        
    print("\n" + "=" * 30)
    print("我的贺卡列表")
    print("=" * 30)
    for idx, ecard in enumerate(my_ecards, 1):
        print(f"{idx}. ID: {ecard['ecard_id']}")
        print(f"   模板: {ecard['template_used']}")
        print(f"   保存时间: {ecard['saved_at']}")
    print("=" * 30)
    
    while True:
        choice = input("请输入要查看的贺卡编号(1-{})，或输入0返回: ".format(len(my_ecards))).strip()
        if choice == "0":
            break
            
        try:
            idx = int(choice) - 1
            if 0 <= idx < len(my_ecards):
                print("\n" + "=" * 30)
                print(f"贺卡内容 (ID: {my_ecards[idx]['ecard_id']})")
                print("=" * 30)
                print(my_ecards[idx]['generated_text'])
                print("=" * 30)
                input("\n按Enter键返回...")
                break
            print("无效的编号，请重新输入！")
        except ValueError:
            print("请输入有效的数字！")
            
def generate_ecard_text(template_content_str, filled_values_dict):
    """
    生成最终贺卡文本
    :param template_content_str: 模板文本
    :param filled_values_dict: 填写的值字典
    :return: 替换后的完整贺卡文本
    """
    result = template_content_str
    for placeholder, value in filled_values_dict.items():
        result = result.replace(placeholder, value)
    return result

def preview_and_generate_ecard_interaction(selected_template, user_filled_values):
    """
    预览并生成贺卡交互
    :param selected_template: 选中的模板
    :param user_filled_values: 用户填写的值
    :return: 生成的贺卡文本
    """
    print("\n" + "=" * 30)
    print("生成的贺卡内容")
    print("=" * 30)
    
    generated_text = generate_ecard_text(
        selected_template['content'], 
        user_filled_values
    )
    print(generated_text)
    print("=" * 30)
    print("贺卡已生成，请复制以上文本内容进行分享！")
    
    return generated_text